
var touches = [];

$(function() {
	$("#touchCnt").text(touches.length + " Touches");	
	$(window).resize(function(){
		resize();
	});
	resize();
	bindEvents('.touchit');
});
function resize(){
	$('#main').width($(window).height()-20);
	$('#main').height($(window).width()-20);
}
function bindEvents(selector){
	//$('#main').bind('touchstart', function() {
	$('body').delegate(selector,'touchstart', function() {
		event.preventDefault();
		var allTouches = event.touches;
		for (var i = 0; i < allTouches.length; i++){
			recordTouch(allTouches[i]);
		}
	});
	//$('#main').bind('touchend', function() {
	$('body').delegate(selector,'touchend', function() {
		event.preventDefault();
		var allTouches = event.touches;
		removeTouch(allTouches);
	});
	//$('#main').bind('touchmove', function() {
	$('body').delegate(selector,'touchmove', function() {
		event.preventDefault();
		var allTouches = event.touches;
		for (var i = 0; i < allTouches.length; i++){
			moveTouch(allTouches[i]);
		}
	});
}
function recordTouch(touch){
	if (newTouch(touch)){
		var template = $('<div class="touch" id="'+ touch.identifier+ '"></div>');
		$('#main').append(template);
		template.css({left: touch.pageX - (template.width() / 2), top: touch.pageY - (template.height() /2) });
		var t = {touch: touch, element: template};	
		touches.push(t);
		return true;
	}
	return false;
}
function moveTouch(touch){
	for (var i = 0; i < touches.length; i++){
		if (touches[i].touch.identifier == touch.identifier){
			touches[i].element.css({left: touch.pageX - (touches[i].element.width() / 2), top: touch.pageY - (touches[i].element.height() /2) });
			return true;
		}
	}
	return false;
}
function newTouch(touch){
	for (var i = 0; i < touches.length; i++){
		if (touches[i].touch.identifier == touch.identifier){
			return false;
		}
	}
	return true;
}
function removeTouch(all_touches){
	var toRemove = [];
	for (var i = 0; i < touches.length; i++){
		var found  = false;
		for (var j = 0; j < all_touches.length; j++ ){
			if (touches[i].touch.identifier == all_touches[j].identifier){
				found = true;
			}
		}
		if (!found){
			toRemove.push({obj: touches[i], ref: i });
		}
	}	
	for (var i = 0; i < toRemove.length; i++){
		for (var j = 0 ; j < touches.length; j++){
			if (touches[j].touch.identifier == toRemove[i].obj.touch.identifier){
				touches.splice(j ,1);
			}
		}
		$(toRemove[i].obj.element).remove();
	}
}